<?php
defined( '_VALID_MOS' ) or die( 'Restricted access' );
error_reporting(E_ALL ^E_NOTICE);
//error_reporting(0);

require_once( dirname( __FILE__ ).'/jcs.functions.php');
require_once( dirname( __FILE__ ).'/joomlaequipment.config.php');
require_once( dirname( __FILE__ ).'/jcstable.php');
$task 	=  mosGetParam( $_REQUEST, 'task', 'view' ) ;
$cid 		= mosGetParam( $_REQUEST, 'cid', array(0) );
if (!is_array( $cid )) { $cid = array(0); }

$juser = (boolean)is_dir($mosConfig_absolute_path.'/administrator/components/com_juser');

$update = $mosConfig_absolute_path.'/administrator/components/com_jcs/update.php';
if(file_exists($update)) include $update;

//echo $task;

switch ($task) {

    case "applayreport":
        jcsReport();
    break;
    case "report":
        jcsReportForm();
    break;

    // manage user subscriptions
    case "us_applay":
    case "us_save":
        jcsUSave();
    case "uedit":
        jcsUEdit($cid[0]);
    break;

    case "uremove":
        jcsUDelete($cid);
        jcsManage();
    break;

    case "upublish":
    case "uunpublish":
        jcsUPublish($cid, $task);
        jcsManage();
    break;
  
    case "new_subscr":
        jcsNewUserSubscription($cid[0]);
    break;
    
    case "save_usubscr":
        jcsSaveUSubscription();
    case "usub":
        jcsManage();
    break;
    
    // manage config
    case "savecnf":
    case "applycnf":
        JEConfig::save($task);
    case "config":
        JEConfig::renderForm(true);
    break;
    
    
    // manage subscriptions
    case "edit":
    case "new":
        jcsNewSubscription($cid[0], $task);
    break;

    case "remove":
        jcsDelete($cid);
        jcsView();
    break;

    case "publish":
    case "unpublish":
        jcsPublish($cid, $task);
        jcsView();
    break;
    case "saveorder":
      saveOrder($cid);
      break;
   
    case "orderdown":
      orderSubscr( intval($cid[0]), 1);
      break;
    case "orderup":
      orderSubscr( intval($cid[0]), -1);
      break;
    case "applaysubscr":
    case "save":
        jcsSave($task);
    case "listsub":
    default:
      jcsView();
}
function jcsReportForm()
{
   global $mosConfig_absolute_path;
   mosCommonHTML::loadCalendar();
   include dirname( __FILE__ )."/views/reports.html.php";
}
function jcsReport()
{
   global $mosConfig_absolute_path;
   include dirname( __FILE__ )."/views/report.html.php";
}

function jcsUSave()
{
    global $database;

    $id    = intval(mosGetParam( $_REQUEST, 'id', FALSE ));
    $task    = mosGetParam( $_REQUEST, 'task', FALSE );
    $access_limit = intval(mosGetParam( $_REQUEST, 'access_limit', 0));
    $published    = intval(mosGetParam( $_REQUEST, 'publish', 0));
    $ctime  = mosGetParam( $_REQUEST, 'ctime', 0);
    $extime = mosGetParam( $_REQUEST, 'extime', 0);
    
    $sql = "
        UPDATE #__jcs_user_subscr SET access_limit = $access_limit, 
        published = $published, ctime = '$ctime', extime = '$extime'
        WHERE id = $id;
    ";
    $database->setQuery( $sql );
    $database->query();
    //echo $sql;

    if($task == 'us_save')
    {
        $link = "index2.php?option=com_jcs&task=usub";
    }
    else
    {
        $link = "index2.php?option=com_jcs&task=uedit&cid[]=".$id;
    }
    mosRedirect($link, 'Subscription Edited Successful');
}
function jcsNewSubscription($cid, $task)
{
    global $database, $acl, $my;
    if($cid)
    {
        $row = new jcsTable( $database );
        $row->load( $cid);
        mosMakeHtmlSafe( $row, ENT_QUOTES, 'description' );
    }
    $query = "SELECT s.id, s.name"
        . "\n FROM #__categories AS s"
        . "\n WHERE section = 'com_jcs_plans'"
        . "\n ORDER BY s.ordering";
    $database->setQuery( $query );    
    
    $categories[] 		= mosHTML::makeOption( '', 'Select Category', 'id', 'name' );
    $categories = array_merge( $categories, $database->loadObjectList() );
    $lists['catid'] 	= mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1"', 'id', 'name', $row->catid );
    
    $my_group = strtolower( $acl->get_group_name( $row->gid, 'ARO' ) );
    if ( $my_group == 'super administrator' && $my->gid != 25 ) {
        $lists['gid'] = '<input type="hidden" name="gid" value="'. $my->gid .'" /><strong>Super Administrator</strong>';
    } else if ( $my->gid == 24 && $row->gid == 24 ) {
        $lists['gid'] = '<input type="hidden" name="gid" value="'. $my->gid .'" /><strong>Administrator</strong>';
    } else {
        // ensure user can't add group higher than themselves
        $my_groups = $acl->get_object_groups( 'users', $my->id, 'ARO' );
        if (is_array( $my_groups ) && count( $my_groups ) > 0) {
            $ex_groups = $acl->get_group_children( $my_groups[0], 'ARO', 'RECURSE' );
        } else {
            $ex_groups = array();
        }
        
        $gtree = $acl->get_group_children_tree( null, 'USERS', false );
        
        // remove users 'above' me
        $i = 0;
        while ($i < count( $gtree )) {
            if (in_array( $gtree[$i]->value, $ex_groups )) {
                array_splice( $gtree, $i, 1 );
            } else {
                $i++;
            }
        }
        
            $lists['gid'] 		= mosHTML::selectList( $gtree, 'gid', 'size="10"', 'value', 'text', $row->gid );
    }
        
    include dirname( __FILE__ )."/views/new.sub.html.php";
}

function jcsNewUserSubscription($cid)
{
    include dirname( __FILE__ )."/views/new.user.sub.html.php";
}
function jcsUEdit($cid)
{
    global $database;
    
    mosCommonHTML::loadOverlib();
		mosCommonHTML::loadCalendar();
    
    if($cid)
    {
        $query = "SELECT u.*, s.name AS sname, s.id AS sid, us.name AS uname, us.id AS uid 
        FROM #__jcs_user_subscr AS u 
        LEFT JOIN #__jcs_plans AS s ON s.id = u.subscription_id 
        LEFT JOIN #__users AS us ON us.id = u.user_id 
        WHERE u.id = '{$cid}'";
        $database->setQuery( $query );
        $rows = $database->loadObjectList();
        $row = $rows[0];
    }
    include dirname( __FILE__ )."/views/edit.user.sub.html.php";
}

function jcsSaveUSubscription()
{
    global $database;
    
    $user    = mosGetParam( $_REQUEST, 'user_id', false ) ;
    $subscr  = mosGetParam( $_REQUEST, 'subscr_id', false ) ;
    $publish = mosGetParam( $_REQUEST, 'publish', false ) ;

    if (!$user || !$subscr) 
    {
        echo "Choose User and Subscription";
        return; 
    }
    $val['id'] = $subscr;
    $val['gateway_id'] = time();
    $val['gateway'] = '.manual';
    
    jcsMakeSubscr($user, $val, $publish, 'index2.php?option=com_jcs&task=usub');
    
}
 

function jcsSave($task)
{
    global $database;
    
    $row = new jcsTable( $database );
    if (!$row->bind( $_POST )) {
      echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
      exit();
    }

    $row->category = @implode(",", mosGetParam( $_REQUEST, 'category', false));
    if(trim($row->category)) $row->type_category = 1;
    
    $components = mosGetParam( $_REQUEST, 'component', NULL);
    if($components)
    {
        $row->type_component = 1;
        foreach($components AS $component)
        {
            $param1 = mosGetParam( $_REQUEST, 'task_'.$component, NULL);
            $param2 = mosGetParam( $_REQUEST, 'value_'.$component, NULL);
            if($param1[0])
            {
                $row->params .= "{$component}:$param1[0]=$param2[0]\n";
            }
            if($param1[1])
            {
                $row->params .= "{$component}:$param1[1]=$param2[1]\n";
            }
        }
        $row->component = @implode(",", $components);
    }
    
    
    if (!$row->catid || !$row->name | !$row->days) {
        echo "<script> alert('Chose category'); window.history.go(-1); </script>\n";
        exit();
    }
    // save usertype to usetype column
    if($row->gid == 29) $row->gid = 0;
    if($row->gid == 30) $row->gid = 0;
    //if($row->gid == 0)  $row->gid = 0;
    
    $query = "SELECT name"
    . "\n FROM #__core_acl_aro_groups"
    . "\n WHERE group_id = " . (int) $row->gid
    ;
    $database->setQuery( $query );
    $usertype = $database->loadResult();
    $row->usertype = ($row->gid == 0) ? '' : $usertype;

    if (!$row->check()) {
        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
        exit();
    }
    
    if (!$row->store()) {
        echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
        exit();
    }
    $row->checkin();
    $row->updateOrder( "catid = " . $row->catid );
    
    if($task == 'save')
    {
        $link = "index2.php?option=com_jcs&task=listsub";
    }
    else
    {
        $link = "index2.php?option=com_jcs&task=edit&cid[]=".$row->id;
    }
    mosRedirect($link, 'Subscription have been saved!');
}

function jcsDelete($cid)
{
    if(!is_array($cid)) return;

    $section = mosGetParam( $_REQUEST, 'section', '' ) ;

    global $database;
    $cids = implode( ',', $cid );
    $query = "DELETE FROM #__jcs_plans WHERE id IN ( {$cids} )";
    $database->setQuery( $query );
    $database->query();
    
    $query = "DELETE FROM #__jcs_user_subscr WHERE subscription_id IN ( {$cids} )";
    $database->setQuery( $query );
    $database->query();
    
}
function jcsUDelete($cid)
{
    if(!is_array($cid)) return;

    global $database;
    $cids = implode( ',', $cid );
    $query = "DELETE FROM #__jcs_user_subscr WHERE id IN ( {$cids} )";
    $database->setQuery( $query );
    $database->query();
}

function orderSubscr( $uid, $inc ) {
	global $database;

	$row = new jcsTable( $database );
	$row->load( (int)$uid );
  //echo $row->name; return;
	$row->move( $inc, "catid = '$row->catid'"  );
	$row->updateOrder("catid = '$row->catid'");
	// clean any existing cache files
	//mosCache::cleanCache( 'com_content' );

	mosRedirect( 'index2.php?option=com_jcs');
}
function saveOrder( &$cid, $section ) {
    global $database;
    
    $total  = count( $cid );
    $order  = mosGetParam($_REQUEST, 'order', array(0));
    
    $row    = new jcsTable( $database );
    $conditions = array();

    // update ordering values
    for( $i=0; $i < $total; $i++ ) {
        $row->load( (int) $cid[$i] );
        if ($row->ordering != $order[$i]) {
            $row->ordering = $order[$i];
            if (!$row->store()) {
                echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
                exit();
            } // if
            // remember to updateOrder this group
            $condition = "catid='$row->catid'";
            $found = false;
            foreach ( $conditions as $cond )
                if ($cond[1]==$condition) {
                    $found = true;
                    break;
                } // if
                if (!$found)
                {
                    $conditions[] = array( $row->id, $condition);
                }
        } // if
    } // for

    // execute updateOrder for each group
    foreach ( $conditions as $cond ) {
    $row->load( $cond[0] );
    $row->updateOrder( $cond[1] );
    } // foreach
    $msg 	= 'New ordering saved';
    mosRedirect( 'index2.php?option=com_jcs', $msg );
} // sav
?>
























<div align="center" style="clear:both">

<small><BR>
<a href="http://joomlaequipment.com">&copy; 2006 "JoomlaEquipment"</a> 
<a href="mailto:support@joomlaequipment.com">Sergey Romanov</a></small></div>
